package com.atguigu.lease.web.admin.custom.Interceptor;

import com.atguigu.lease.common.login.LoginUser;
import com.atguigu.lease.common.login.LoginUserHolder;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //根据key获取请求头中的token值
        String token= request.getHeader("access-token");
        //解析token  获得负载部分
        Claims claims = JwtUtil.parseToken(token);
        //获取得到的声明
        LoginUser loginUser = new LoginUser(claims.get("userId",Long.class),claims.get("username", String.class));
            //将username保存在线程中  这样就可以用username查找用户了   而不需要在方法中解析再获得username  LoginUserHolder避免了两次token的解析
        LoginUserHolder.setLoginUser(loginUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserHolder.clear();
    }
}
